{% extends "pc/template.html" %}

{% block title %}
商品列表
{% endblock %}

{% include 'pc/公共样式配置/CSS总样式.html' %}

{% block css %}
<link rel="stylesheet" href="/static/HubUI/css/sweetalert2.css">
<style>
    /* SweetAlert2 层级样式 */
    .swal2-container {
        z-index: 99999 !important;
    }
    .swal2-popup {
        z-index: 99999 !important;
    }
    .swal2-backdrop-show {
        z-index: 99998 !important;
    }
    /* 确保模态框的z-index不会超过SweetAlert2 */
    .modal {
        z-index: 1050;
    }
    .modal-backdrop {
        z-index: 1040;
    }
    .card {
        margin: 1.5rem 0;
        border: none;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        border-radius: 0.5rem;
        transition: all 0.3s ease;
    }
    .card:hover {
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1);
    }
    .card-header {
        background: #fff;
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        padding: 1.25rem 1.5rem;
        border-radius: 0.5rem 0.5rem 0 0;
    }
    .card-header h5 {
        color: #566a7f;
        font-weight: 600;
        margin: 0;
    }
    .table-responsive {
        margin: 0;
        padding: 0 1.5rem;
    }
    .table {
        margin: 1rem 0;
        border-collapse: separate;
        border-spacing: 0;
    }
    .table th {
        background: #f8f9fa;
        color: #566a7f;
        font-weight: 600;
        padding: 1rem;
        border-bottom: 2px solid #e9ecef;
        white-space: nowrap;
    }
    .table td {
        padding: 1rem;
        vertical-align: middle;
        border-bottom: 1px solid #e9ecef;
        color: #697a8d;
        transition: all 0.2s ease;
    }
    .table tbody tr {
        transition: all 0.2s ease;
    }
    .table tbody tr:hover {
        background-color: #f8f9fa;
        transform: translateY(-1px);
    }
    .action-buttons .btn {
        padding: 0.375rem 0.75rem;
        margin: 0 0.25rem;
        border-radius: 0.375rem;
        transition: all 0.2s ease;
    }
    .action-buttons .btn:hover {
        transform: translateY(-1px);
    }
    .btn-info {
        background-color: #71ddff;
        border-color: #71ddff;
        color: #fff;
    }
    .btn-info:hover {
        background-color: #4fd4ff;
        border-color: #4fd4ff;
    }
    .btn-danger {
        background-color: #ff8590;
        border-color: #ff8590;
    }
    .btn-danger:hover {
        background-color: #ff6b78;
        border-color: #ff6b78;
    }
    .status-badge {
        padding: 0.5em 0.75em;
        font-size: 0.75em;
        font-weight: 600;
        border-radius: 0.375rem;
        display: inline-block;
        text-align: center;
        min-width: 80px;
    }
    .status-normal {
        background-color: #e8fff3;
        color: #28c76f;
        border: 1px solid #28c76f;
    }
    .status-off {
        background-color: #ffe4e4;
        color: #ea5455;
        border: 1px solid #ea5455;
    }
    .product-image {
        width: 60px;
        height: 60px;
        object-fit: cover;
        border-radius: 0.5rem;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;
    }
    .product-image:hover {
        transform: scale(1.1);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
    }
    .description-text {
        display: inline-block;
        max-width: 100px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        cursor: help;
        vertical-align: middle;
        color: #697a8d;
        transition: all 0.2s ease;
        position: relative;
    }
    .description-text:hover {
        color: #566a7f;
    }
    .description-text:hover::after {
        content: attr(data-full-text);
        position: absolute;
        left: 0;
        top: 100%;
        background: #fff;
        padding: 0.5rem;
        border-radius: 0.375rem;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        z-index: 99999;
        white-space: normal;
        width: 300px;
        max-height: 200px;
        overflow-y: auto;
        font-size: 0.875rem;
        line-height: 1.5;
        margin-top: 0.5rem;
        border: 1px solid #e9ecef;
    }
    .description-text:hover::before {
        content: '';
        position: absolute;
        left: 10px;
        top: calc(100% - 5px);
        border-width: 0 5px 5px 5px;
        border-style: solid;
        border-color: transparent transparent #fff transparent;
        z-index: 99999;
    }
    .form-check-input {
        width: 1.25em;
        height: 1.25em;
        margin-top: 0.125em;
        cursor: pointer;
        transition: all 0.2s ease;
    }
    .form-check-input:checked {
        background-color: #696cff;
        border-color: #696cff;
    }
    .form-check-input:focus {
        border-color: #696cff;
        box-shadow: 0 0 0 0.25rem rgba(105, 108, 255, 0.25);
    }
    .pagination {
        margin: 1.5rem 0;
        justify-content: center;
    }
    .pagination .page-link {
        padding: 0.5rem 0.75rem;
        color: #566a7f;
        background-color: #fff;
        border: 1px solid #d9dee3;
        margin: 0 0.25rem;
        border-radius: 0.375rem;
        transition: all 0.2s ease;
    }
    .pagination .page-item.active .page-link {
        background-color: #696cff;
        border-color: #696cff;
        color: #fff;
    }
    .pagination .page-link:hover {
        color: #696cff;
        background-color: #f5f5f9;
        border-color: #d9dee3;
        transform: translateY(-1px);
    }
    .pagination .page-item.disabled .page-link {
        color: #a3a4cc;
        pointer-events: none;
        background-color: #fff;
        border-color: #d9dee3;
    }
    .btn-primary {
        background-color: #696cff;
        border-color: #696cff;
        color: #fff;
        padding: 0.5rem 1rem;
        border-radius: 0.375rem;
        transition: all 0.2s ease;
    }
    .btn-primary:hover {
        background-color: #5f61e6;
        border-color: #5f61e6;
        transform: translateY(-1px);
    }
    .btn-outline-secondary {
        color: #697a8d;
        border-color: #d9dee3;
        padding: 0.5rem 1rem;
        border-radius: 0.375rem;
        transition: all 0.2s ease;
    }
    .btn-outline-secondary:hover {
        background-color: #f5f5f9;
        border-color: #d9dee3;
        color: #566a7f;
        transform: translateY(-1px);
    }
    .modal-content {
        border: none;
        border-radius: 0.5rem;
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
    }
    .modal-header {
        background-color: #f8f9fa;
        border-bottom: 1px solid #e9ecef;
        padding: 1.25rem 1.5rem;
        border-radius: 0.5rem 0.5rem 0 0;
    }
    .modal-title {
        color: #566a7f;
        font-weight: 600;
    }
    .modal-body {
        padding: 1.5rem;
    }
    .form-label {
        color: #566a7f;
        font-weight: 500;
        margin-bottom: 0.5rem;
    }
    .form-control {
        border: 1px solid #d9dee3;
        border-radius: 0.375rem;
        padding: 0.5rem 0.75rem;
        transition: all 0.2s ease;
    }
    .form-control:focus {
        border-color: #696cff;
        box-shadow: 0 0 0 0.25rem rgba(105, 108, 255, 0.25);
    }
    .form-select {
        border: 1px solid #d9dee3;
        border-radius: 0.375rem;
        padding: 0.5rem 0.75rem;
        transition: all 0.2s ease;
    }
    .form-select:focus {
        border-color: #696cff;
        box-shadow: 0 0 0 0.25rem rgba(105, 108, 255, 0.25);
    }
    .text-danger {
        color: #ff8590 !important;
    }
    .text-muted {
        color: #a3a4cc !important;
    }
    .image-preview-container {
        margin-top: 1.5rem;
        padding: 1.5rem;
        border: 1px solid #e9ecef;
        border-radius: 0.5rem;
        background: #f8f9fa;
    }
    .image-preview-title {
        font-size: 1rem;
        color: #566a7f;
        font-weight: 600;
        margin-bottom: 1rem;
    }
    .product-images-preview {
        display: flex;
        flex-wrap: wrap;
        gap: 1rem;
        margin-top: 1rem;
    }
    .product-image-item {
        position: relative;
        width: 120px;
        height: 120px;
        border-radius: 0.5rem;
        overflow: hidden;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;
    }
    .product-image-item:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
    }
    .product-image-item img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    .delete-image {
        position: absolute;
        top: 0.5rem;
        right: 0.5rem;
        background: rgba(255, 255, 255, 0.9);
        border-radius: 50%;
        width: 28px;
        height: 28px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        color: #ff8590;
        font-size: 1.25rem;
        border: none;
        padding: 0;
        transition: all 0.2s ease;
    }
    .delete-image:hover {
        background: #ff8590;
        color: white;
        transform: scale(1.1);
    }
    .image-upload-container {
        margin-top: 1rem;
    }
    .image-upload-container .form-control {
        padding: 0.375rem;
    }
    .image-upload-container .form-label {
        margin-bottom: 0.5rem;
    }
    .image-preview-scroll {
        max-height: 300px;
        overflow-y: auto;
        padding-right: 0.5rem;
    }
    .image-preview-scroll::-webkit-scrollbar {
        width: 6px;
    }
    .image-preview-scroll::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 3px;
    }
    .image-preview-scroll::-webkit-scrollbar-thumb {
        background: #d9dee3;
        border-radius: 3px;
    }
    .image-preview-scroll::-webkit-scrollbar-thumb:hover {
        background: #a3a4cc;
    }
    .swal2-popup {
        border-radius: 0.5rem;
        padding: 1.5rem;
    }
    .swal2-title {
        color: #566a7f;
        font-weight: 600;
    }
    .swal2-html-container {
        color: #697a8d;
    }
    .swal2-confirm {
        background-color: #696cff !important;
        border-radius: 0.375rem !important;
    }
    .swal2-cancel {
        background-color: #f5f5f9 !important;
        color: #697a8d !important;
        border-radius: 0.375rem !important;
    }
    /* 下拉菜单样式 */
    .dropdown-menu {
        border: none;
        border-radius: 0.5rem;
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
        padding: 0.5rem;
        min-width: 160px;
    }
    
    .dropdown-item {
        padding: 0.6rem 1rem;
        color: #697a8d;
        border-radius: 0.4rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
        transition: all 0.2s ease;
    }
    
    .dropdown-item:hover {
        background: #f8f9fa;
        color: #566a7f;
    }
    
    .dropdown-item i {
        font-size: 1.1rem;
    }
    
    .dropdown-item.edit {
        color: #ffab00;
    }
    
    .dropdown-item.delete {
        color: #ff3e1d;
    }
    
    .dropdown-item.edit:hover {
        background: rgba(255, 171, 0, 0.1);
    }
    
    .dropdown-item.delete:hover {
        background: rgba(255, 62, 29, 0.1);
    }
    
    .dropdown-toggle::after {
        display: none;
    }
    
    .action-btn {
        background: #f8f9fa;
        border: 1px solid #d9dee3;
        color: #697a8d;
        padding: 0.4rem 0.8rem;
        border-radius: 0.5rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
        transition: all 0.2s ease;
    }
    
    .action-btn:hover {
        background: #f5f5f9;
        border-color: #d9dee3;
        color: #566a7f;
    }
    
    .action-btn i {
        font-size: 1.1rem;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-xxl flex-grow-1 container-p-y">
    <!-- 商品列表卡片 -->
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">商品列表</h5>
            <div>
                <button type="button" class="btn btn-danger me-2" onclick="batchDeleteProducts()" id="batchDeleteBtn" style="display: none;">
                    <i class="bx bx-trash"></i> 批量删除
                </button>
                <button type="button" class="btn btn-primary" onclick="showAddProductModal()">
                    <i class="bx bx-plus"></i> 添加商品
                </button>
            </div>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="selectAll" onclick="toggleSelectAll()">
                                </div>
                            </th>
                            <th>ID</th>
                            <th>图片</th>
                            <th>名称</th>
                            <th>分类</th>
                            <th>价格</th>
                            <th>库存</th>
                            <th>货架数量</th>
                            <th>仓库数量</th>
                            <th>状态</th>
                            <th>上架员</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="productTableBody">
                        <!-- 商品数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
            <!-- 分页控件 -->
            <nav aria-label="Page navigation">
                <ul class="pagination" id="pagination">
                    <!-- 分页按钮将通过JavaScript动态加载 -->
                </ul>
            </nav>
        </div>
    </div>

    <!-- 添加商品模态框 -->
    <div class="modal fade" id="addProductModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加商品</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="addProductForm">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label" for="productName">商品名称 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="productName" name="name" required maxlength="30">
                                    <small class="text-muted">商品名称不能超过30个字符</small>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label" for="productId">商品ID</label>
                                    <input type="text" class="form-control" id="productId" name="product_id">
                                    <small class="text-muted">商品ID为可选字段</small>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label" for="productCategory">主分类</label>
                                    <select class="form-select" id="productCategory" name="category">
                                        <option value="">请选择主分类</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label" for="productCategorySub">次分类</label>
                                    <select class="form-select" id="productCategorySub" name="category_sub">
                                        <option value="">请选择次分类</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label" for="productPrice">价格 <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="productPrice" name="price" step="0.01" min="0.01" required>
                                    <small class="text-muted">商品价格必须大于0</small>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label" for="productPurchasePrice">进货价 <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="productPurchasePrice" name="purchase_price" step="0.01" min="0.01" required>
                                    <small class="text-muted">进货价必须大于0</small>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label" for="productStock">库存 <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="productStock" name="stock" min="0" required>
                                    <small class="text-muted">商品库存不能小于0</small>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label" for="productShelfNumber">货架数量 <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="productShelfNumber" name="shelf_number" min="0" required>
                                    <small class="text-muted">货架数量不能小于0</small>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label" for="productWarehouseNumber">仓库数量 <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="productWarehouseNumber" name="warehouse_number" min="0" required>
                                    <small class="text-muted">仓库数量不能小于0</small>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label" for="productStatus">状态 <span class="text-danger">*</span></label>
                                    <select class="form-select" id="productStatus" name="status" required>
                                        <option value="1">正常</option>
                                        <option value="2">下架</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label" for="productShelfStaff">上架员 <span class="text-danger">*</span></label>
                                    <select class="form-select" id="productShelfStaff" name="shelf_staff" required>
                                        <option value="">请选择上架员</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label" for="productDescription">描述</label>
                                    <textarea class="form-control" id="productDescription" name="description" rows="3"></textarea>
                                </div>
                            </div>
                        </div>
                        <!-- 商品图片上传区域 -->
                        <div class="image-preview-container">
                            <div class="image-preview-title">商品图片</div>
                            <div class="image-upload-container">
                                <label class="form-label" for="productImages">添加商品图片</label>
                                <input type="file" class="form-control" id="productImages" name="images" multiple accept="image/*">
                                <small class="text-muted">可以选择多张图片上传</small>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="addProduct()">添加</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑商品模态框 -->
    <div class="modal fade" id="editProductModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑商品</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="editProductForm">
                        <input type="hidden" id="editProductHiddenId">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label" for="editProductName">商品名称</label>
                                    <input type="text" class="form-control" id="editProductName" name="name" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label" for="editProductId">商品ID</label>
                                    <input type="text" class="form-control" id="editProductId" name="product_id" readonly>
                                    <small class="text-muted">商品ID不可编辑</small>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label" for="editProductCategory">主分类</label>
                                    <select class="form-select" id="editProductCategory" name="category">
                                        <option value="">请选择主分类</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label" for="editProductCategorySub">次分类</label>
                                    <select class="form-select" id="editProductCategorySub" name="category_sub">
                                        <option value="">请选择次分类</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label" for="editProductPrice">价格</label>
                                    <input type="number" class="form-control" id="editProductPrice" name="price" step="0.01" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label" for="editProductPurchasePrice">进货价</label>
                                    <input type="number" class="form-control" id="editProductPurchasePrice" name="purchase_price" step="0.01" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label" for="editProductStock">库存</label>
                                    <input type="number" class="form-control" id="editProductStock" name="stock" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label" for="editProductShelfNumber">货架数量</label>
                                    <input type="number" class="form-control" id="editProductShelfNumber" name="shelf_number" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label" for="editProductWarehouseNumber">仓库数量</label>
                                    <input type="number" class="form-control" id="editProductWarehouseNumber" name="warehouse_number" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label" for="editProductStatus">状态</label>
                                    <select class="form-select" id="editProductStatus" name="status">
                                        <option value="1">正常</option>
                                        <option value="2">下架</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label" for="editProductShelfStaff">上架员</label>
                                    <select class="form-select" id="editProductShelfStaff" name="shelf_staff" required>
                                        <option value="">请选择上架员</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label" for="editProductDescription">描述</label>
                                    <textarea class="form-control" id="editProductDescription" name="description" rows="3"></textarea>
                                </div>
                            </div>
                        </div>
                        <!-- 商品图片预览和管理区域 -->
                        <div class="image-preview-container">
                            <div class="image-preview-title">商品图片</div>
                            <div class="image-preview-scroll">
                                <div id="editProductImagesPreview" class="product-images-preview">
                                    <!-- 图片预览将通过JavaScript动态加载 -->
                                </div>
                            </div>
                            <div class="image-upload-container">
                                <label class="form-label" for="editProductImages">添加新图片</label>
                                <input type="file" class="form-control" id="editProductImages" name="images" multiple accept="image/*">
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="updateProduct()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 兄弟商品管理模态框 -->
    <div class="modal fade" id="brotherProductsModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">管理兄弟商品</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row mb-3">
                        <div class="col-md-8">
                            <div class="input-group">
                                <input type="text" class="form-control" id="brotherProductSearch" placeholder="搜索商品...">
                                <button class="btn btn-primary" type="button" onclick="searchBrotherProducts()">
                                    <i class="bx bx-search"></i> 搜索
                                </button>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <button class="btn btn-success w-100" onclick="showAddBrotherProductModal()">
                                <i class="bx bx-plus"></i> 添加兄弟商品
                            </button>
                        </div>
                    </div>
                    <div class="table-responsive">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>商品名称</th>
                                    <th>价格</th>
                                    <th>库存</th>
                                    <th>状态</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="brotherProductsTableBody">
                                <!-- 兄弟商品列表将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加兄弟商品模态框 -->
    <div class="modal fade" id="addBrotherProductModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加兄弟商品</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <!-- 搜索栏 -->
                    <div class="row mb-3">
                        <div class="col-md-8">
                            <div class="input-group">
                                <input type="text" class="form-control" id="availableProductSearch" placeholder="搜索商品...">
                                <button class="btn btn-primary" type="button" onclick="searchAvailableProducts()">
                                    <i class="bx bx-search"></i> 搜索
                                </button>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="checkbox" id="selectAllAvailable" onclick="toggleSelectAllAvailable()">
                                <label class="form-check-label" for="selectAllAvailable">全选</label>
                            </div>
                        </div>
                    </div>
                    <!-- 商品列表 -->
                    <div class="table-responsive" style="max-height: 400px; overflow-y: auto;">
                        <table class="table">
                            <thead class="sticky-top bg-white">
                                <tr>
                                    <th style="width: 50px;">选择</th>
                                    <th>商品名称</th>
                                    <th>价格</th>
                                    <th>库存</th>
                                    <th>状态</th>
                                </tr>
                            </thead>
                            <tbody id="availableProductsTableBody">
                                <!-- 可选商品列表将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                    </div>
                    <!-- 分页控件 -->
                    <nav aria-label="Page navigation" class="mt-3">
                        <ul class="pagination justify-content-center" id="availableProductsPagination">
                            <!-- 分页按钮将通过JavaScript动态加载 -->
                        </ul>
                    </nav>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="addBrotherProducts()">添加</button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
    let currentProduct = null; // 存储当前编辑的商品数据
    let allProducts = []; // 存储所有商品数据
    let currentPage = 1; // 当前页码
    const itemsPerPage = 10; // 每页显示的数量
    let currentProductId = null; // 存储当前正在管理兄弟关系的商品ID

    let availableProductsPage = 1;
    const availableProductsPerPage = 10;
    let filteredAvailableProducts = [];

    // 页面加载完成后获取商品列表、分类列表和用户列表
    document.addEventListener('DOMContentLoaded', function() {
        getProductList();
        getCategoryList();
        getUserList();
    });

    // 获取用户列表
    function getUserList() {
        axios.get('/api/users/get_user_list/')
            .then(function(response) {
                if (response.data.code === 200) {
                    updateUserOptions(response.data.data);
                }
            });
    }

    // 更新用户选项
    function updateUserOptions(users) {
        const userSelects = [
            document.getElementById('productShelfStaff'),
            document.getElementById('editProductShelfStaff')
        ];

        const options = users.map(user => 
            `<option value="${user.id}">${user.username}</option>`
        ).join('');

        userSelects.forEach(select => {
            if (select) {
                select.innerHTML = '<option value="">请选择上架员</option>' + options;
            }
        });
    }

    // 获取商品列表
    function getProductList() {
        const loadingToast = Swal.fire({
            title: '加载中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        axios.get('/api/product/get_product_list/')
            .then(function(response) {
                if (response.data.code === 200) {
                    allProducts = response.data.data;
                    currentPage = 1; // 重置到第一页
                    renderProductTable();
                    renderPagination();
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                Swal.fire('错误', '获取商品列表失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 获取分类列表
    function getCategoryList() {
        Promise.all([
            axios.get('/api/category/get_category_list/'),
            axios.get('/api/category/get_category_sub_list/')
        ]).then(function([mainResponse, subResponse]) {
            if (mainResponse.data.code === 200 && subResponse.data.code === 200) {
                updateCategoryOptions(mainResponse.data.data, subResponse.data.data);
            }
        });
    }

    // 更新分类选项
    function updateCategoryOptions(mainCategories, subCategories) {
        const mainCategorySelects = [
            document.getElementById('productCategory'),
            document.getElementById('editProductCategory')
        ];
        const subCategorySelects = [
            document.getElementById('productCategorySub'),
            document.getElementById('editProductCategorySub')
        ];

        // 更新主分类选项
        const mainOptions = mainCategories.map(category => 
            `<option value="${category.id}">${category.name}</option>`
        ).join('');
        mainCategorySelects.forEach(select => {
            if (select) {
                select.innerHTML = '<option value="">请选择主分类</option>' + mainOptions;
            }
        });

        // 更新次分类选项
        const subOptions = subCategories.map(category => 
            `<option value="${category.id}" data-parent="${category.parent}">${category.name}</option>`
        ).join('');
        subCategorySelects.forEach(select => {
            if (select) {
                select.innerHTML = '<option value="">请选择次分类</option>' + subOptions;
            }
        });

        // 添加分类选择事件监听
        mainCategorySelects.forEach(select => {
            if (select) {
                select.addEventListener('change', function() {
                    const formId = this.id.startsWith('edit') ? 'edit' : 'add';
                    const subSelect = document.getElementById(`${formId}ProductCategorySub`);
                    if (this.value) {
                        // 如果选择了主分类，清空次分类选择
                        subSelect.value = '';
                        // 显示提示
                        Swal.fire({
                            icon: 'info',
                            title: '提示',
                            text: '已选择主分类，次分类将被清空',
                            showConfirmButton: false,
                            timer: 1500
                        });
                    }
                });
            }
        });

        subCategorySelects.forEach(select => {
            if (select) {
                select.addEventListener('change', function() {
                    const formId = this.id.startsWith('edit') ? 'edit' : 'add';
                    const mainSelect = document.getElementById(`${formId}ProductCategory`);
                    if (this.value) {
                        // 如果选择了次分类，清空主分类选择
                        mainSelect.value = '';
                        // 显示提示
                        Swal.fire({
                            icon: 'info',
                            title: '提示',
                            text: '已选择次分类，主分类将被清空',
                            showConfirmButton: false,
                            timer: 1500
                        });
                    }
                });
            }
        });
    }

    // 渲染商品表格
    function renderProductTable() {
        const tbody = document.getElementById('productTableBody');
        tbody.innerHTML = '';

        // 计算当前页的数据
        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = startIndex + itemsPerPage;
        const currentPageProducts = allProducts.slice(startIndex, endIndex);

        currentPageProducts.forEach(product => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>
                    <div class="form-check">
                        <input class="form-check-input product-checkbox" type="checkbox" value="${product.id}">
                    </div>
                </td>
                <td>${product.id}</td>
                <td>
                    ${product.images && product.images.length > 0 ? 
                        `<img src="${product.images[0].image}" class="product-image" alt="${product.name}">` : 
                        '<span class="text-muted">无图片</span>'}
                </td>
                <td>${product.name}</td>
                <td>${product.category_name || product.category_sub_name || '-'}</td>
                <td>￥${product.price}</td>
                <td>${product.stock}</td>
                <td>${product.shelf_number || 0}</td>
                <td>${product.warehouse_number || 0}</td>
                <td>
                    <span class="status-badge ${product.status === 1 ? 'status-normal' : 'status-off'}">
                        ${product.status === 1 ? '正常' : '下架'}
                    </span>
                </td>
                <td>${product.shelf_staff_name || '-'}</td>
                <td class="action-buttons">
                    <div class="dropdown">
                        <button class="action-btn dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="bx bx-dots-vertical-rounded"></i>
                            <span>操作</span>
                        </button>
                        <ul class="dropdown-menu">
                            <li>
                                <a class="dropdown-item edit" href="#" onclick="editProduct(${product.id})">
                                    <i class="bx bx-edit"></i>
                                    <span>编辑</span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item" href="#" onclick="manageBrotherProducts(${product.id})">
                                    <i class="bx bx-link"></i>
                                    <span>兄弟商品</span>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item delete" href="#" onclick="deleteProduct(${product.id})">
                                    <i class="bx bx-trash"></i>
                                    <span>删除</span>
                                </a>
                            </li>
                        </ul>
                    </div>
                </td>
            `;
            tbody.appendChild(tr);
        });
    }

    // 渲染分页控件
    function renderPagination() {
        const pagination = document.getElementById('pagination');
        const totalPages = Math.ceil(allProducts.length / itemsPerPage);
        
        let paginationHTML = '';
        
        // 上一页按钮
        paginationHTML += `
            <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="changePage(${currentPage - 1})" aria-label="Previous">
                    <i class="bx bx-chevron-left"></i>
                </a>
            </li>
        `;

        // 页码按钮
        for (let i = 1; i <= totalPages; i++) {
            paginationHTML += `
                <li class="page-item ${currentPage === i ? 'active' : ''}">
                    <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
                </li>
            `;
        }

        // 下一页按钮
        paginationHTML += `
            <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="changePage(${currentPage + 1})" aria-label="Next">
                    <i class="bx bx-chevron-right"></i>
                </a>
            </li>
        `;

        pagination.innerHTML = paginationHTML;
    }

    // 切换页码
    function changePage(page) {
        if (page < 1 || page > Math.ceil(allProducts.length / itemsPerPage)) {
            return;
        }
        currentPage = page;
        renderProductTable();
        renderPagination();
    }

    // 显示添加商品模态框
    function showAddProductModal() {
        const modal = new bootstrap.Modal(document.getElementById('addProductModal'));
        document.getElementById('addProductForm').reset();
        modal.show();
    }

    // 添加商品
    async function addProduct() {
        const form = document.getElementById('addProductForm');
        const formData = new FormData(form);
        
        // 验证必填字段
        const name = formData.get('name');
        const price = formData.get('price');
        const purchase_price = formData.get('purchase_price');
        const stock = formData.get('stock');
        const status = formData.get('status');
        const shelf_staff = formData.get('shelf_staff');
        const category = formData.get('category');
        const category_sub = formData.get('category_sub');
        const shelf_number = formData.get('shelf_number');
        const warehouse_number = formData.get('warehouse_number');

        if (!name || !price || !purchase_price || !stock || !status || !shelf_staff || !shelf_number || !warehouse_number) {
            Swal.fire('错误', '请填写所有必填字段', 'error');
            return;
        }

        // 验证数量关系
        if (parseInt(shelf_number) < 0 || parseInt(warehouse_number) < 0) {
            Swal.fire('错误', '货架数量和仓库数量不能为负数', 'error');
            return;
        }

        if (parseInt(shelf_number) + parseInt(warehouse_number) !== parseInt(stock)) {
            Swal.fire('错误', '货架数量和仓库数量之和必须等于库存', 'error');
            return;
        }

        // 验证进货价和售卖价的关系
        if (parseFloat(purchase_price) >= parseFloat(price)) {
            const result = await Swal.fire({
                title: '价格确认',
                text: '进货价大于或等于售卖价，是否确认继续？',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: '确认',
                cancelButtonText: '取消'
            });
            if (!result.isConfirmed) {
                return;
            }
        }

        // 验证分类选择
        if (!category && !category_sub) {
            Swal.fire({
                icon: 'warning',
                title: '分类选择',
                text: '请选择主分类或次分类',
                confirmButtonText: '确定'
            });
            return;
        }

        if (category && category_sub) {
            Swal.fire({
                icon: 'warning',
                title: '分类选择',
                text: '商品不能同时属于主分类和次分类，请只选择其中一个',
                confirmButtonText: '确定'
            });
            return;
        }

        // 转换数据类型
        const data = {
            name: name,
            price: parseFloat(price),
            purchase_price: parseFloat(purchase_price),
            stock: parseInt(stock),
            status: parseInt(status),
            shelf_staff: parseInt(shelf_staff),
            description: formData.get('description') || '',
            product_id: formData.get('product_id') || null,
            shelf_number: parseInt(shelf_number),
            warehouse_number: parseInt(warehouse_number)
        };

        // 添加分类信息
        if (category) {
            data.category = parseInt(category);
        }
        if (category_sub) {
            data.category_sub = parseInt(category_sub);
        }

        // 立即关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('addProductModal'));
        modal.hide();

        const loadingToast = Swal.fire({
            title: '添加中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        // 先创建商品
        axios.post('/api/product/create_product/', data)
            .then(function(response) {
                if (response.data.code === 200) {
                    // 如果有图片，上传图片
                    const images = document.getElementById('productImages').files;
                    if (images.length > 0) {
                        const productId = response.data.data.id;
                        const imagePromises = Array.from(images).map(image => {
                            const imageFormData = new FormData();
                            imageFormData.append('product', productId);
                            imageFormData.append('image', image);
                            return axios.post(`/api/product/upload_product_image/${productId}/`, imageFormData);
                        });
                        return Promise.all(imagePromises);
                    }
                    return Promise.resolve();
                } else {
                    throw new Error(response.data.msg);
                }
            })
            .then(function() {
                Swal.fire({
                    icon: 'success',
                    title: '成功',
                    text: '商品添加成功',
                    showConfirmButton: false,
                    timer: 1500
                }).then(() => {
                    getProductList();
                    form.reset();
                });
            })
            .catch(function(error) {
                Swal.fire('错误', error.message || '添加商品失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 编辑商品
    function editProduct(productId) {
        const loadingToast = Swal.fire({
            title: '加载中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        axios.get(`/api/product/get_product/${productId}/`)
            .then(function(response) {
                if (response.data.code === 200) {
                    const product = response.data.data;
                    currentProduct = product; // 保存当前商品数据
                    
                    document.getElementById('editProductHiddenId').value = productId;
                    document.getElementById('editProductName').value = product.name;
                    document.getElementById('editProductId').value = product.product_id || '';
                    document.getElementById('editProductCategory').value = product.category || '';
                    document.getElementById('editProductCategorySub').value = product.category_sub || '';
                    document.getElementById('editProductPrice').value = product.price;
                    document.getElementById('editProductPurchasePrice').value = product.purchase_price || '';
                    document.getElementById('editProductStock').value = product.stock;
                    document.getElementById('editProductShelfNumber').value = product.shelf_number || '';
                    document.getElementById('editProductWarehouseNumber').value = product.warehouse_number || '';
                    document.getElementById('editProductStatus').value = product.status;
                    document.getElementById('editProductShelfStaff').value = product.shelf_staff;
                    document.getElementById('editProductDescription').value = product.description || '';

                    // 渲染商品图片预览
                    renderProductImages(product.images || []);

                    const modal = new bootstrap.Modal(document.getElementById('editProductModal'));
                    modal.show();
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                Swal.fire('错误', '获取商品信息失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 渲染商品图片预览
    function renderProductImages(images) {
        const container = document.getElementById('editProductImagesPreview');
        container.innerHTML = '';

        if (!images || images.length === 0) {
            container.innerHTML = '<div class="text-muted">暂无商品图片</div>';
            return;
        }

        images.forEach(image => {
            const imageItem = document.createElement('div');
            imageItem.className = 'product-image-item';
            imageItem.innerHTML = `
                <img src="${image.image}" alt="商品图片">
                <button type="button" class="delete-image" onclick="deleteProductImage(${image.id})">
                    <i class="bx bx-x"></i>
                </button>
            `;
            container.appendChild(imageItem);
        });
    }

    // 删除商品图片
    function deleteProductImage(imageId) {
        Swal.fire({
            title: '确认删除',
            text: '确定要删除这张图片吗？',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            allowOutsideClick: false,
            allowEscapeKey: false
        }).then((result) => {
            if (result.isConfirmed) {
                const loadingToast = Swal.fire({
                    title: '删除中...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                axios.delete(`/api/product/delete_product_image/${imageId}/`)
                    .then(function(response) {
                        if (response.data.code === 200) {
                            // 获取当前商品ID
                            const productId = document.getElementById('editProductHiddenId').value;
                            
                            // 获取商品图片列表
                            return axios.get(`/api/product/get_product_images/${productId}/`)
                                .then(function(imageResponse) {
                                    if (imageResponse.data.code === 200) {
                                        // 更新图片预览
                                        renderProductImages(imageResponse.data.data);
                                        
                                        // 显示成功提示
                                        Swal.fire({
                                            icon: 'success',
                                            title: '成功',
                                            text: '图片删除成功',
                                            showConfirmButton: false,
                                            timer: 1500
                                        });
                                    } else {
                                        throw new Error(imageResponse.data.msg);
                                    }
                                });
                        } else {
                            throw new Error(response.data.msg);
                        }
                    })
                    .catch(function(error) {
                        Swal.fire('错误', error.message || '删除图片失败', 'error');
                    })
                    .finally(function() {
                        loadingToast.close();
                        // 确保移除所有遮罩层
                        document.querySelectorAll('.swal2-backdrop-show').forEach(el => el.remove());
                    });
            }
        });
    }

    // 更新商品
    async function updateProduct() {
        const productId = document.getElementById('editProductHiddenId').value;
        const form = document.getElementById('editProductForm');
        const formData = new FormData(form);
        const data = Object.fromEntries(formData.entries());

        // 验证分类选择
        const category = formData.get('category');
        const category_sub = formData.get('category_sub');
        const shelf_number = formData.get('shelf_number');
        const warehouse_number = formData.get('warehouse_number');

        if (!category && !category_sub) {
            Swal.fire({
                icon: 'warning',
                title: '分类选择',
                text: '请选择主分类或次分类',
                confirmButtonText: '确定'
            });
            return;
        }

        if (category && category_sub) {
            Swal.fire({
                icon: 'warning',
                title: '分类选择',
                text: '商品不能同时属于主分类和次分类，请只选择其中一个',
                confirmButtonText: '确定'
            });
            return;
        }

        // 验证数量关系
        if (parseInt(shelf_number) < 0 || parseInt(warehouse_number) < 0) {
            Swal.fire('错误', '货架数量和仓库数量不能为负数', 'error');
            return;
        }

        if (parseInt(shelf_number) + parseInt(warehouse_number) !== parseInt(data.stock)) {
            Swal.fire('错误', '货架数量和仓库数量之和必须等于库存', 'error');
            return;
        }

        // 验证进货价和售卖价的关系
        const purchase_price = parseFloat(data.purchase_price);
        const price = parseFloat(data.price);
        if (purchase_price >= price) {
            const result = await Swal.fire({
                title: '价格确认',
                text: '进货价大于或等于售卖价，是否确认继续？',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: '确认',
                cancelButtonText: '取消'
            });
            if (!result.isConfirmed) {
                return;
            }
        }

        // 使用当前商品数据填充未填写的字段
        if (!data.name) data.name = currentProduct.name;
        if (!data.price) data.price = currentProduct.price;
        if (!data.purchase_price) data.purchase_price = currentProduct.purchase_price;
        if (!data.stock) data.stock = currentProduct.stock;
        if (!data.status) data.status = currentProduct.status;
        if (!data.shelf_staff) data.shelf_staff = currentProduct.shelf_staff;
        if (!data.description) data.description = currentProduct.description;
        if (!data.shelf_number) data.shelf_number = currentProduct.shelf_number;
        if (!data.warehouse_number) data.warehouse_number = currentProduct.warehouse_number;

        // 处理分类数据
        if (category) {
            data.category = parseInt(category);
            data.category_sub = null; // 如果选择了主分类，确保次分类为null
        } else if (category_sub) {
            data.category = null; // 如果选择了次分类，确保主分类为null
            data.category_sub = parseInt(category_sub);
        }

        // 转换数据类型
        data.status = parseInt(data.status);
        data.stock = parseInt(data.stock);
        data.price = parseFloat(data.price);
        data.purchase_price = parseFloat(data.purchase_price);
        data.shelf_staff = parseInt(data.shelf_staff);
        data.shelf_number = parseInt(data.shelf_number);
        data.warehouse_number = parseInt(data.warehouse_number);

        // 立即关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('editProductModal'));
        modal.hide();

        const loadingToast = Swal.fire({
            title: '更新中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        // 先更新商品基本信息
        axios.post(`/api/product/update_product/${productId}/`, data)
            .then(function(response) {
                if (response.data.code === 200) {
                    // 如果有新图片，上传图片
                    const images = document.getElementById('editProductImages').files;
                    if (images.length > 0) {
                        const imagePromises = Array.from(images).map(image => {
                            const imageFormData = new FormData();
                            imageFormData.append('product', productId);
                            imageFormData.append('image', image);
                            return axios.post(`/api/product/upload_product_image/${productId}/`, imageFormData);
                        });
                        return Promise.all(imagePromises);
                    }
                    return Promise.resolve();
                } else {
                    throw new Error(response.data.msg);
                }
            })
            .then(function() {
                Swal.fire({
                    icon: 'success',
                    title: '成功',
                    text: '商品更新成功',
                    showConfirmButton: false,
                    timer: 1500
                }).then(() => {
                    getProductList();
                });
            })
            .catch(function(error) {
                Swal.fire('错误', error.message || '更新商品失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 删除商品
    function deleteProduct(productId) {
        Swal.fire({
            title: '确认删除',
            text: '确定要删除这个商品吗？',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }).then((result) => {
            if (result.isConfirmed) {
                const loadingToast = Swal.fire({
                    title: '删除中...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                axios.delete(`/api/product/delete_product/${productId}/`)
                    .then(function(response) {
                        if (response.data.code === 200) {
                            Swal.fire({
                                icon: 'success',
                                title: '成功',
                                text: '商品删除成功',
                                showConfirmButton: false,
                                timer: 1500
                            }).then(() => {
                                getProductList();
                            });
                        } else {
                            Swal.fire('错误', response.data.msg, 'error');
                        }
                    })
                    .catch(function(error) {
                        Swal.fire('错误', '删除商品失败', 'error');
                    })
                    .finally(function() {
                        loadingToast.close();
                    });
            }
        });
    }

    // 切换全选/取消全选
    function toggleSelectAll() {
        const selectAllCheckbox = document.getElementById('selectAll');
        const checkboxes = document.getElementsByClassName('product-checkbox');
        const batchDeleteBtn = document.getElementById('batchDeleteBtn');
        
        Array.from(checkboxes).forEach(checkbox => {
            checkbox.checked = selectAllCheckbox.checked;
        });
        
        // 显示/隐藏批量删除按钮
        batchDeleteBtn.style.display = selectAllCheckbox.checked ? 'inline-block' : 'none';
    }

    // 监听单个复选框变化
    document.addEventListener('change', function(e) {
        if (e.target.classList.contains('product-checkbox')) {
            const checkboxes = document.getElementsByClassName('product-checkbox');
            const selectAllCheckbox = document.getElementById('selectAll');
            const batchDeleteBtn = document.getElementById('batchDeleteBtn');
            
            // 检查是否所有复选框都被选中
            const allChecked = Array.from(checkboxes).every(checkbox => checkbox.checked);
            selectAllCheckbox.checked = allChecked;
            
            // 检查是否有任何复选框被选中
            const anyChecked = Array.from(checkboxes).some(checkbox => checkbox.checked);
            batchDeleteBtn.style.display = anyChecked ? 'inline-block' : 'none';
        }
    });

    // 批量删除商品
    function batchDeleteProducts() {
        const checkboxes = document.getElementsByClassName('product-checkbox');
        const selectedIds = Array.from(checkboxes)
            .filter(checkbox => checkbox.checked)
            .map(checkbox => checkbox.value);

        if (selectedIds.length === 0) {
            Swal.fire('提示', '请选择要删除的商品', 'info');
            return;
        }

        Swal.fire({
            title: '确认删除',
            text: `确定要删除选中的 ${selectedIds.length} 个商品吗？`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }).then((result) => {
            if (result.isConfirmed) {
                const loadingToast = Swal.fire({
                    title: '删除中...',
                    text: '正在删除商品，请稍候',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                // 使用 Promise.all 处理所有删除请求
                const deletePromises = selectedIds.map(id => 
                    axios.delete(`/api/product/delete_product/${id}/`)
                );

                Promise.all(deletePromises)
                    .then(() => {
                        Swal.fire({
                            icon: 'success',
                            title: '成功',
                            text: `成功删除 ${selectedIds.length} 个商品`,
                            showConfirmButton: false,
                            timer: 1500
                        }).then(() => {
                            getProductList();
                        });
                    })
                    .catch((error) => {
                        Swal.fire('错误', '删除商品时发生错误', 'error');
                    })
                    .finally(() => {
                        loadingToast.close();
                    });
            }
        });
    }

    // 管理兄弟商品
    function manageBrotherProducts(productId) {
        currentProductId = productId;
        // 获取当前商品的product_id
        const product = allProducts.find(p => p.id === productId);
        if (!product || !product.product_id) {
            Swal.fire('错误', '商品ID不存在', 'error');
            return;
        }
        const modal = new bootstrap.Modal(document.getElementById('brotherProductsModal'));
        loadBrotherProducts(product.product_id);
        modal.show();
    }

    // 加载兄弟商品列表
    function loadBrotherProducts(productId) {
        const loadingToast = Swal.fire({
            title: '加载中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        axios.get(`/api/product/brother/get_product_brother/${productId}/`)
            .then(function(response) {
                if (response.data.code === 200) {
                    const tbody = document.getElementById('brotherProductsTableBody');
                    tbody.innerHTML = '';

                    response.data.data.forEach(brother => {
                        const tr = document.createElement('tr');
                        tr.innerHTML = `
                            <td>${brother.name}</td>
                            <td>￥${brother.price}</td>
                            <td>${brother.stock}</td>
                            <td>
                                <span class="status-badge ${brother.status === 1 ? 'status-normal' : 'status-off'}">
                                    ${brother.status === 1 ? '正常' : '下架'}
                                </span>
                            </td>
                            <td>
                                <button class="btn btn-danger btn-sm" onclick="removeBrotherProduct('${brother.product_id}')">
                                    <i class="bx bx-trash"></i> 移除
                                </button>
                            </td>
                        `;
                        tbody.appendChild(tr);
                    });
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                Swal.fire('错误', '获取兄弟商品列表失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 显示添加兄弟商品模态框
    function showAddBrotherProductModal() {
        const modal = new bootstrap.Modal(document.getElementById('addBrotherProductModal'));
        availableProductsPage = 1;
        loadAvailableProducts();
        modal.show();
    }

    // 加载可选商品列表
    function loadAvailableProducts() {
        const loadingToast = Swal.fire({
            title: '加载中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        // 获取当前商品的product_id
        const currentProduct = allProducts.find(p => p.id === currentProductId);
        if (!currentProduct || !currentProduct.product_id) {
            Swal.fire('错误', '商品ID不存在', 'error');
            return;
        }

        // 先获取所有商品
        axios.get('/api/product/get_product_list/')
            .then(function(response) {
                if (response.data.code === 200) {
                    // 获取当前商品的兄弟商品列表
                    return axios.get(`/api/product/brother/get_product_brother/${currentProduct.product_id}/`)
                        .then(function(brotherResponse) {
                            if (brotherResponse.data.code === 200) {
                                // 获取已经是兄弟关系的商品ID列表
                                const brotherProductIds = brotherResponse.data.data.map(brother => brother.product_id);
                                
                                // 过滤掉当前商品和已经是兄弟关系的商品
                                filteredAvailableProducts = response.data.data.filter(product => {
                                    return product.id !== currentProductId && 
                                           product.product_id && 
                                           !brotherProductIds.includes(product.product_id);
                                });
                                
                                renderAvailableProducts();
                            } else {
                                throw new Error(brotherResponse.data.msg);
                            }
                        });
                } else {
                    throw new Error(response.data.msg);
                }
            })
            .catch(function(error) {
                Swal.fire('错误', error.message || '获取商品列表失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 渲染可选商品列表
    function renderAvailableProducts() {
        const tbody = document.getElementById('availableProductsTableBody');
        tbody.innerHTML = '';

        const startIndex = (availableProductsPage - 1) * availableProductsPerPage;
        const endIndex = startIndex + availableProductsPerPage;
        const currentPageProducts = filteredAvailableProducts.slice(startIndex, endIndex);

        currentPageProducts.forEach(product => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>
                    <div class="form-check">
                        <input class="form-check-input product-checkbox" type="checkbox" value="${product.id}">
                    </div>
                </td>
                <td>${product.name}</td>
                <td>￥${product.price}</td>
                <td>${product.stock}</td>
                <td>
                    <span class="status-badge ${product.status === 1 ? 'status-normal' : 'status-off'}">
                        ${product.status === 1 ? '正常' : '下架'}
                    </span>
                </td>
            `;
            tbody.appendChild(tr);
        });

        renderAvailableProductsPagination();
    }

    // 渲染分页控件
    function renderAvailableProductsPagination() {
        const pagination = document.getElementById('availableProductsPagination');
        const totalPages = Math.ceil(filteredAvailableProducts.length / availableProductsPerPage);
        
        let paginationHTML = '';
        
        // 上一页按钮
        paginationHTML += `
            <li class="page-item ${availableProductsPage === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="changeAvailableProductsPage(${availableProductsPage - 1})" aria-label="Previous">
                    <i class="bx bx-chevron-left"></i>
                </a>
            </li>
        `;

        // 页码按钮
        for (let i = 1; i <= totalPages; i++) {
            paginationHTML += `
                <li class="page-item ${availableProductsPage === i ? 'active' : ''}">
                    <a class="page-link" href="#" onclick="changeAvailableProductsPage(${i})">${i}</a>
                </li>
            `;
        }

        // 下一页按钮
        paginationHTML += `
            <li class="page-item ${availableProductsPage === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" onclick="changeAvailableProductsPage(${availableProductsPage + 1})" aria-label="Next">
                    <i class="bx bx-chevron-right"></i>
                </a>
            </li>
        `;

        pagination.innerHTML = paginationHTML;
    }

    // 切换可选商品页码
    function changeAvailableProductsPage(page) {
        if (page < 1 || page > Math.ceil(filteredAvailableProducts.length / availableProductsPerPage)) {
            return;
        }
        availableProductsPage = page;
        renderAvailableProducts();
    }

    // 切换全选/取消全选
    function toggleSelectAllAvailable() {
        const selectAllCheckbox = document.getElementById('selectAllAvailable');
        const checkboxes = document.querySelectorAll('#availableProductsTableBody .product-checkbox');
        
        Array.from(checkboxes).forEach(checkbox => {
            checkbox.checked = selectAllCheckbox.checked;
        });
    }

    // 搜索可选商品
    function searchAvailableProducts() {
        const searchText = document.getElementById('availableProductSearch').value.trim().toLowerCase();
        if (!searchText) {
            loadAvailableProducts();
            return;
        }

        const loadingToast = Swal.fire({
            title: '搜索中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        // 获取当前商品的product_id
        const currentProduct = allProducts.find(p => p.id === currentProductId);
        if (!currentProduct || !currentProduct.product_id) {
            Swal.fire('错误', '商品ID不存在', 'error');
            return;
        }

        // 先搜索商品
        axios.get(`/api/product/search_product/?name=${encodeURIComponent(searchText)}`)
            .then(function(response) {
                if (response.data.code === 200) {
                    // 获取当前商品的兄弟商品列表
                    return axios.get(`/api/product/brother/get_product_brother/${currentProduct.product_id}/`)
                        .then(function(brotherResponse) {
                            if (brotherResponse.data.code === 200) {
                                // 获取已经是兄弟关系的商品ID列表
                                const brotherProductIds = brotherResponse.data.data.map(brother => brother.product_id);
                                
                                // 过滤掉当前商品和已经是兄弟关系的商品
                                filteredAvailableProducts = response.data.data.filter(product => {
                                    return product.id !== currentProductId && 
                                           product.product_id && 
                                           !brotherProductIds.includes(product.product_id);
                                });
                                
                                availableProductsPage = 1;
                                renderAvailableProducts();
                            } else {
                                throw new Error(brotherResponse.data.msg);
                            }
                        });
                } else {
                    throw new Error(response.data.msg);
                }
            })
            .catch(function(error) {
                Swal.fire('错误', error.message || '搜索商品失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 检查商品是否是兄弟关系
    function isBrotherProduct(productId) {
        const currentProduct = allProducts.find(p => p.id === currentProductId);
        if (!currentProduct || !currentProduct.product_id) return false;

        // 这里可以添加缓存机制，避免重复请求
        return new Promise((resolve) => {
            axios.get(`/api/product/brother/check_product_brother/${currentProduct.product_id}/${productId}/`)
                .then(function(response) {
                    resolve(response.data.code === 200 && response.data.data.is_brother);
                })
                .catch(() => {
                    resolve(false);
                });
        });
    }

    // 添加兄弟商品
    function addBrotherProducts() {
        const checkboxes = document.querySelectorAll('#availableProductsTableBody .product-checkbox:checked');
        if (checkboxes.length === 0) {
            Swal.fire('提示', '请选择要添加的兄弟商品', 'info');
            return;
        }

        const loadingToast = Swal.fire({
            title: '添加中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        // 获取当前商品的product_id
        const currentProduct = allProducts.find(p => p.id === currentProductId);
        if (!currentProduct || !currentProduct.product_id) {
            Swal.fire('错误', '商品ID不存在', 'error');
            return;
        }

        // 获取选中的商品
        const selectedProducts = Array.from(checkboxes).map(checkbox => {
            const product = filteredAvailableProducts.find(p => p.id === parseInt(checkbox.value));
            if (!product || !product.product_id) {
                throw new Error(`商品 ${product?.name || checkbox.value} 的ID不存在`);
            }
            return product;
        });

        // 创建添加兄弟商品的请求
        const promises = selectedProducts.map(product => {
            const data = {
                product: currentProduct.product_id,
                brother_product: product.product_id
            };
            return axios.post('/api/product/brother/create_product_brother/', data);
        });

        Promise.all(promises)
            .then(function() {
                Swal.fire({
                    icon: 'success',
                    title: '成功',
                    text: '添加兄弟商品成功',
                    showConfirmButton: false,
                    timer: 1500
                }).then(() => {
                    // 关闭添加模态框
                    const addModal = bootstrap.Modal.getInstance(document.getElementById('addBrotherProductModal'));
                    addModal.hide();
                    // 刷新兄弟商品列表
                    loadBrotherProducts(currentProduct.product_id);
                });
            })
            .catch(function(error) {
                Swal.fire('错误', error.message || '添加兄弟商品失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 移除兄弟商品
    function removeBrotherProduct(brotherId) {
        Swal.fire({
            title: '确认移除',
            text: '确定要移除这个兄弟商品吗？',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }).then((result) => {
            if (result.isConfirmed) {
                const loadingToast = Swal.fire({
                    title: '移除中...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                // 获取当前商品的product_id
                const currentProduct = allProducts.find(p => p.id === currentProductId);
                if (!currentProduct || !currentProduct.product_id) {
                    Swal.fire('错误', '商品ID不存在', 'error');
                    return;
                }

                axios.delete(`/api/product/brother/delete_product_brother/${currentProduct.product_id}/${brotherId}/`)
                    .then(function(response) {
                        if (response.data.code === 200) {
                            Swal.fire({
                                icon: 'success',
                                title: '成功',
                                text: '移除兄弟商品成功',
                                showConfirmButton: false,
                                timer: 1500
                            }).then(() => {
                                loadBrotherProducts(currentProduct.product_id);
                            });
                        } else {
                            Swal.fire('错误', response.data.msg, 'error');
                        }
                    })
                    .catch(function(error) {
                        Swal.fire('错误', '移除兄弟商品失败', 'error');
                    })
                    .finally(function() {
                        loadingToast.close();
                    });
            }
        });
    }

    // 搜索兄弟商品
    function searchBrotherProducts() {
        const searchText = document.getElementById('brotherProductSearch').value.trim();
        if (!searchText) {
            // 获取当前商品的product_id
            const currentProduct = allProducts.find(p => p.id === currentProductId);
            if (!currentProduct || !currentProduct.product_id) {
                Swal.fire('错误', '商品ID不存在', 'error');
                return;
            }
            loadBrotherProducts(currentProduct.product_id);
            return;
        }

        const loadingToast = Swal.fire({
            title: '搜索中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        // 获取当前商品的product_id
        const currentProduct = allProducts.find(p => p.id === currentProductId);
        if (!currentProduct || !currentProduct.product_id) {
            Swal.fire('错误', '商品ID不存在', 'error');
            return;
        }

        axios.get(`/api/product/search_product/?name=${encodeURIComponent(searchText)}`)
            .then(function(response) {
                if (response.data.code === 200) {
                    const tbody = document.getElementById('brotherProductsTableBody');
                    tbody.innerHTML = '';

                    response.data.data.forEach(product => {
                        // 检查是否是当前商品的兄弟商品
                        axios.get(`/api/product_brother/check_product_brother/${currentProduct.product_id}/${product.product_id}/`)
                            .then(function(checkResponse) {
                                if (checkResponse.data.code === 200 && checkResponse.data.data.is_brother) {
                                    const tr = document.createElement('tr');
                                    tr.innerHTML = `
                                        <td>${product.name}</td>
                                        <td>￥${product.price}</td>
                                        <td>${product.stock}</td>
                                        <td>
                                            <span class="status-badge ${product.status === 1 ? 'status-normal' : 'status-off'}">
                                                ${product.status === 1 ? '正常' : '下架'}
                                            </span>
                                        </td>
                                        <td>
                                            <button class="btn btn-danger btn-sm" onclick="removeBrotherProduct('${product.product_id}')">
                                                <i class="bx bx-trash"></i> 移除
                                            </button>
                                        </td>
                                    `;
                                    tbody.appendChild(tr);
                                }
                            });
                    });
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                Swal.fire('错误', '搜索商品失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }
</script>
{% endblock %}

{% block nav_left %}
{% include "pc/components/左侧导航栏.html" %}
{% endblock %}

{% block NavBar %}
{% endblock %}

{% include 'pc/公共样式配置/JS总样式.html' %}

{% block footer %}
    {% include "pc/components/Footer.html" %}
{% endblock %}